<template>
  <div class="index-conntainer">
    <div class="content">
      
    
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item :label="t('userinfo.userName')" prop="name">
              <el-input
                v-model="queryParams.name"
                :placeholder="t('userinfo.userName')"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            
            <el-form-item :label="t('userinfo.status')" prop="status">
               <el-select v-model="queryParams.status"  :placeholder="t('common.choose')"  clearable>
                  <el-option
                    v-for="item in statusList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="handleQuery()"><i-ep-search />{{ t('common.search') }}</el-button>
              <el-button @click="resetQuery()"><i-ep-refresh />{{ t('common.reset') }}</el-button>
            </el-form-item>
          </el-form>
        </div>
     
     
     <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                 <el-button
                    type="primary"
                    plain
                    :icon="Plus"
                    @click="handleAdd">{{ t('common.add') }}</el-button>
              </el-col>
              <el-col :span="1.5">
                 <el-button
                    type="success"
                    plain
                   icon="Edit"
                   :disabled="single"
                   @click="handlerUpdate()"
                 >{{ t('common.modi') }}</el-button>
              </el-col>
              
              <el-col :span="1.5">
                  <el-button
                     type="danger"
                     plain
                     icon="Delete"
                     :disabled="multiple"
                     @click="handlerDelete()"
                  >{{ t('common.remove') }}</el-button>
               </el-col>
          
           </el-row>
     
       <el-table v-loading="loading" :data="rows" @selection-change="handleSelectionChange" >            
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column :label="t('common.id')" align="center" prop="id" />
            <el-table-column :label="t('userinfo.userName')" align="center" prop="name" />
            <el-table-column :label="t('userinfo.sex')" align="center">
               <template #default="scope">
                 <el-tag  effect="dark" v-if="scope.row.sex.trim()=='1'">{{t('userinfo.man')}}</el-tag>
                  <el-tag type="success" effect="dark" v-else>{{t('userinfo.woman')}}</el-tag>                  
               </template>              
            </el-table-column>
            <el-table-column :label="t('userinfo.age')" align="center" prop="age" />
            <el-table-column :label="t('userinfo.mobile')" align="center" prop="mobile" /> 
            <el-table-column :label="t('userinfo.portrait')" align="center" prop="portrait" width="200">  
              <template #default="scope">
                 <img :src="scope.row.portrait"  width="150">            
              </template>     
            </el-table-column>
            <el-table-column :label="t('userinfo.status')" align="center" prop="status" >    
               <template #default="scope">
                 <el-tag  effect="dark" v-if="scope.row.status.trim()=='0'">{{t('common.normal')}}</el-tag>
                  <el-tag type="danger" effect="dark" v-else>{{t('common.disable')}}</el-tag>                  
               </template>              
            </el-table-column>
           
            <el-table-column :label="t('common.operate')" width="180" align="center" class-name="small-padding fixed-width">
               <template #default="scope">
                  <el-button link type="primary" icon="Edit" @click="handlerUpdate(scope.row)"  >{{t('common.modi')}}</el-button>
                  <el-button link type="primary" icon="Delete"  @click="handlerDelete(scope.row)" >{{t('common.remove')}}</el-button>
               </template>
            </el-table-column>
         </el-table>
    
          <el-pagination
               v-if="total>0"
               v-model:current-page="queryParams.page"
               v-model:page-size="queryParams.size"
               :page-sizes="[10, 20, 30, 40,50,100]"
               small="small"
               layout="total, sizes, prev, pager, next, jumper"
               :total="total"
               @size-change="handleSizeChange"
               @current-change="handleCurrentChange"
             />
    
         <!-- 添加或修改岗位对话框 -->
            <el-dialog :title="title" v-model="open" width="700px" append-to-body :close-on-click-modal="false" @closed="reset">
                 <el-form ref="postRef" :model="form"   label-width="80px">
                     <el-form-item v-if="!form.id" label="账号" prop="name"  :rules="[{ required: true, message: '该值不能为空', trigger: 'blur' }]">
                        <el-input v-model="form.name" placeholder="请输入账号" />
                     </el-form-item>
                     
                     <el-form-item v-if="!form.id" label="密码" prop="password" :rules="[{ required: true, message: '该值不能为空', trigger: 'blur' }]">
                       <el-input type="password" v-model="form.password" placeholder="请输入密码名称" />
                    </el-form-item>
                    
                    <el-form-item v-if="!form.id" label="确认密码" prop="confirmPwd" :rules="[{ required: true, message: '该值不能为空', trigger: 'blur' },{validator:validatePass2,trigger: 'blur'}]">
                       <el-input type="password" v-model="form.confirmPwd" placeholder="请输入再次输入名称" />
                    </el-form-item>
                    
                    <el-form-item label="性别" prop="sex" :rules="[{ required: true, message: '该值不能为空', trigger: 'blur' }]">
                        <el-radio-group v-model="form.sex">
                           <el-radio
                              v-for="sex in sexList"
                              :key="sex.value"
                              :label="sex.value"
                           >{{ sex.label }}</el-radio>
                        </el-radio-group>
                     </el-form-item>
                     
                     
                     <el-form-item v-if="!form.id" label="手机号" prop="mobile" :rules="[{ required: true, message: '该值不能为空', trigger: 'blur' },{validator:mobileValidator,trigger: 'blur'}]">
                         <el-input  v-model="form.mobile" placeholder="请输入手机号" />
                      </el-form-item>
                      
                      <el-form-item label="年龄" prop="age" :rules="[{ required: true, message: '该值不能为空', trigger: 'blur' }]">
                         <el-input  v-model="form.age" placeholder="请输入年龄" />
                      </el-form-item>
                      
                      <el-form-item label="头像" prop="portrait" :rules="[{ required: true, message: '该值不能为空', trigger: 'blur' }]">
                        <el-upload
                            class="avatar-uploader"
                            action="http://localhost:8080/api/upload/image"
                            :headers="header"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload"
                          >
                            <img v-if="form.portrait" :src="form.portrait" class="avatar" width="175" />
                            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                          </el-upload>
                      </el-form-item>
                      
                      
                      <el-form-item label="状态" prop="status" :rules="[{ required: true, message: '该值不能为空', trigger: 'blur' }]">
                         <el-radio-group v-model="form.status">
                            <el-radio
                               v-for="dict in statusList"
                               :key="dict.value"
                               :label="dict.value"
                            >{{ dict.label }}</el-radio>
                         </el-radio-group>
                      </el-form-item>
                    
                  </el-form>
               <template #footer>
                  <div class="dialog-footer">
                     <el-button type="primary" @click="submitForm">确 定</el-button>
                     <el-button @click="cancelForm">取 消</el-button>
                  </div>
               </template>
            </el-dialog>
    </div>
    
    </div>
</template>

<script setup >
  import { ref} from 'vue'
  import { Plus } from '@element-plus/icons-vue' 
  import { ElMessage } from 'element-plus'
  import store from '@/store/index.js'
  //定义国际化的语言的文件
  import { useI18n } from 'vue-i18n';
  const { t } = useI18n();
  
  //组合式函数(代码重复的问题)
  import { usePage } from '@/composables/PageComp.js'
  import { useAddAndEdit } from '@/composables/AddAndEditComp.js'
  
  //自定义函数   这里要变变@/api/名称
  import { dataApi, addApi, updateApi ,findByIdApi, removeApi} from "@/api/user";
  
  const { proxy } = getCurrentInstance();
       
   
  //通用数据必须要有的
  const reactiveObject = ref({
     dataApi: dataApi,
     addApi: addApi,
     updateApi: updateApi,
     findByIdApi: findByIdApi,
     removeApi: removeApi,
     proxy: proxy,
     //这里要变，主键名称
     primaryKey: 'id'
    }); 
     
  //分页查询
  const { loading, total,rows ,queryParams,ids,single,multiple , handleQuery, resetQuery, handleSizeChange , handleCurrentChange, getList,handleSelectionChange }=usePage(reactiveObject)
  //新增和修改
  const { open,title,form,reset,cancelForm,submitForm,handlerUpdate,handleAdd ,beforeAvatarUpload ,handlerDelete}=useAddAndEdit(reactiveObject)
  
   //------------------------------------ 以下是可选项---------------------------------
   //自己的定义额外参数
  const data = reactive({
    header: {
      'Authorization': store.getters['user/accessToken']
    },
    statusList: [
      { value:'0', label: '正常'},
      { value:'1', label: '禁用'}
    ],
    sexList: [
      { value:'0', label: '女'},
      { value:'1', label: '男'}
    ],
  });
  
  ///自己的定义额外参数,用来使用的
  const { statusList, sexList, header} = toRefs(data);
  
  
  //初始化新装和修改的对话框的数据(必须要有)
  function initFormData(){
    form.value= {
      portrait: undefined,
      sex: '0',
      status: '0'
    }
  }
  
  initFormData()
   
  
  //文件上传成功
  function handleAvatarSuccess(res, file) {
    if(res.code===200){
       form.value.portrait= res.data.image_url
    }else{
       ElMessage.error( res.msg);
    } 
   } 
  
   //自定义表单验证（实际情况来选项配置）
    function validatePass2(rule, value, callback) { 
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== form.value.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    }
    
    //自定义表单验证 （实际情况来选项配置）
    function mobileValidator(rule, value, callback){
      const regex=/1[3,4,5,6,8,9]\d{9}/ 
      if (value === '') {
        callback(new Error('手机号不能为空'));
      } else if (!regex.test(value)) {
        callback(new Error('手机号码格式不正确，只支持(13|14|15|17|18|19)开头的!'));
      } else {
        callback();
      }
    }
 
   
</script>

<style lang="scss" scoped>
  .index-conntainer {
    width: $base-width;
     background-color: $base-color-white;
    .head-card {
      display: flex;
      align-items: center;
      padding: $base-main-padding;
      background-color: $base-color-white;
      &-content {
        padding-left: 15px;
        .desc {
          color: $base-font-color;
        }
      }
    }
    
    .mb8{
   
      padding: 15px;
    }
    
    .search-container{
      padding: 15px;
    }
    .content {
      background-color: $base-color-white;
      margin: 15px 0;
      .count-box {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .item {
          display: flex;
          flex-direction: column;
          text-align: center;
          .label {
            padding: 10px 0;
            font-size: $base-font-size-big;
          }
          .count {
            font-size: $base-font-size-max;
            font-weight: bolder;
            color: $base-color-primary;
            &.error {
              color: var(--el-color-danger);
            }
            &.success {
              color: var(--el-color-success);
            }
          }
        }
      } 
       
    }
  }
  
</style>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed  #858486;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }
  
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
</style>
